// 拿药
import {useNavigate, useParams} from "react-router-dom";
import {
    Box,
    Button,
    Drawer, DrawerBody, DrawerCloseButton,
    DrawerContent, DrawerFooter, DrawerHeader,
    DrawerOverlay, FormLabel, Input,
    Stack, Text,
    useColorModeValue,
    useDisclosure,
    useToast
} from "@chakra-ui/react";
import {useAuth} from "../../hooks/index.js";
import React, {useEffect, useState} from "react";
import {findOrderById} from "../../api/order.js";
import {getMedicineItems, listByStudentId, medicineListOver, uptMedicineListItemNum} from "../../api/medicineList.js";
import {findByName, getAllMedicine, getAllMedicinePage} from "../../api/medicine.js";
import {handleResult, handleResultNoRoute} from "../../api/result.js";
import ManageSearchBar from "../../components/ManageSearchBar.jsx";
import {EditIcon} from "@chakra-ui/icons";

export function TakeMedicinePage() {
    const navigator = useNavigate()
    const toast = useToast()
    // 登录后会有学生信息
    const authInfo = JSON.parse(localStorage.getItem('auth-info'))

    // 数据获取
    const [mhs, setMhs] = useState([]) // 药单list
    const [medicineItems, setMedicineItems] = useState([])
    const [total, setTotal] = useState([])
    useEffect(() => {
        console.log(authInfo)
        // 请求数据
        listByStudentId(authInfo.student.id).then(r => {
            console.log(r.data)
            setMhs(r.data)
        })
    }, []);

    // ManageSearchBar states
    const [value, setValue] = useState('')
    let timer = new Date()
    const [startDate, setStartDate] = useState(timer.toLocaleDateString())
    const [endDate, setEndDate] = useState(timer.toLocaleDateString())

    let searchItem = {
        placeholder: '药品名称',
        value,
        onChange: (e) => {
            setValue(e.target.value)
        },
        onClick: (e) => {
            if (value === '') {
                getAllMedicine().then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setMedicines(r.data)
                })
                return
            }
            findByName(value).then(r => {
                handleResultNoRoute(r, toast, '', '查询成功')
                setMedicines(r.data)
            })
        }
    }
    let dateSearchItem = {
        onChange: (date, dateString) => {
            console.log(date, dateString)
            setStartDate(dateString[0])
            setEndDate(dateString[1])
        },
        onClick: (e) => {
            console.log(startDate, endDate)
        }
    }
    // 当前页码
    const [curIdx, setCurIdx] = useState(0);
    let pageSearchItem = {
        total: (Math.floor(total / 6) + 1), curIdx,
        onChange: (e) => {
            setCurIdx(e.target.value)
        },
        onLeftClick: () => {
            console.log(curIdx)
            if (curIdx > 1) {
                setCurIdx((curIdx - 1))
                return
            }
            toast({
                title: `已到达第一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onRightClick: () => {
            if (curIdx < (Math.floor(total / 6) + 1)) {
                setCurIdx((curIdx + 1))
                return
            }
            toast({
                title: `已到达最后一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onClick: () => {
            console.log(curIdx)
            getAllMedicinePage({page: curIdx, size: 6})
                .then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setMedicines(r.data)
                })
        }
    }

    // 添加按钮 弹出drawer
    const {isOpen, onOpen, onClose} = useDisclosure()
    // 用于弹出时聚焦
    const firstField = React.useRef()

    // 跳转药品列表选择添加
    function onAddClick() {
        navigator(`/doctor/manage/medicine/add/${parseInt(orderId)}`)
    }

    // drawer里的表单的数据
    const [name, setName] = useState('')
    const [number, setNumber] = useState(0)
    const [mid, setMid] = useState(1)

    // 操作栏
    function handleUptClick(id, name, num) {
        setMid(id)
        setName(name)
        setNumber(num)
        onOpen()
    }

    // 确认药单添加完成
    function handlerOver() {
        // order status -> 已开药
        // medicine history -> 设置总价格
        medicineListOver({orderId, price})
            .then(r => handleResult(r, toast, '',
                '开单成功', 'doctor/manage/order'))
        // 返回叫号页面
        // navigator('/doctor/manage/order')
    }

    return (
        <Stack
            align={'start'}
            justify={'start'}
            spacing={4}
            mb={6}
            className={useColorModeValue('', 'dark')}>
            <ManageSearchBar
                onAddClick={onAddClick}
                pageSearchItem={pageSearchItem}
                searchItem={searchItem}
                dateSearchItem={dateSearchItem}/>
            <div className={"table-container "}>
                <table className="table table-hover">
                    <thead>
                    <tr>
                        <th>药单id</th>
                        {/*<th>药品分类</th>*/}
                        <th>开药医生</th>
                        <th>价格</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        mhs.map((item) => (
                                <tr key={item.medicineHistoryId}>
                                    <td>{item.medicineHistoryId}</td>
                                    {/*<td>{item.medicine.category}</td>*/}
                                    <td>{item.doctorName}</td>
                                    <td>{item.totalPrice}</td>
                                    <td>
                                        <Stack direction='row' spacing={4}>
                                            <Button
                                                onClick={() =>
                                                    navigator(
                                                        `/student/take/medicine/pay/${item.medicineHistoryId}`)}
                                                leftIcon={<EditIcon/>} size='sm'
                                                colorScheme='teal' variant='solid'>
                                                支付
                                            </Button>
                                            <Button
                                                onClick={() =>
                                                    navigator(
                                                        `/student/take/medicine/detail/${item.medicineHistoryId}`)}
                                                leftIcon={<EditIcon/>} size='sm'
                                                colorScheme='teal' variant='solid'>
                                                详情
                                            </Button>
                                        </Stack>
                                    </td>
                                </tr>
                            )
                        )
                    }
                    </tbody>
                </table>
            </div>
            {/*  drawer修改数量  */}
            <Drawer
                size={'md'}
                isOpen={isOpen}
                placement='right'
                initialFocusRef={firstField}
                onClose={onClose}
            >
                <DrawerOverlay/>
                <DrawerContent>
                    <DrawerCloseButton/>
                    <DrawerHeader borderBottomWidth='1px'>
                        修改药品数量
                    </DrawerHeader>

                    <DrawerBody>
                        <Stack spacing='24px'>
                            <Box>
                                <Text>{name}</Text>
                            </Box>
                            <Box>
                                <FormLabel htmlFor='category'>药品数量</FormLabel>
                                <Input
                                    onChange={(e) => setNumber(e.target.value)}
                                    value={number} type="number"/>
                            </Box>
                        </Stack>
                    </DrawerBody>

                    <DrawerFooter borderTopWidth='1px'>
                        <Button variant='outline' mr={3} onClick={onClose}>
                            取消
                        </Button>
                        <Button onClick={() => {
                            console.log(mid, name, number)
                            uptMedicineListItemNum({mid, number})
                                .then(r => handleResult(r, toast, '', '修改成功'))
                        }} colorScheme='blue'>提交</Button>
                    </DrawerFooter>
                </DrawerContent>
            </Drawer>
        </Stack>
    )
}